package org.lmind.example.util.text;

import java.util.ArrayList;

public class TextReplacement {

	private ArrayList<Replacement> replacements = new ArrayList<Replacement>();
	
	public void add(int start, int end, String replacement) {
		
		if (start < 0 || start > end || replacement == null)
			throw new IllegalArgumentException();
		if (replacements.size() > 0) {
			if (replacements.get(replacements.size()-1).end > start) {
				throw new IllegalArgumentException();
			}
		}
		
		Replacement r = new Replacement();
		r.start = start;
		r.end = end;
		r.replacement = replacement;
		replacements.add(r);
	}
	
	public String apply(String text) {
		StringBuilder sb = new StringBuilder();
		
		int offset = 0;
		for (Replacement item : replacements) {
			sb.append(text.substring(offset, item.start));
			sb.append(item.replacement);
			offset = item.end;
		}
		sb.append(text.substring(offset));
		return sb.toString();
	}
	
	class Replacement {
		private String replacement;
		private int start;
		private int end;
	}
}
